package com.hyg.lib_music.ui.fragment;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hyg.lib_base.Net.NetworkUtils;
import com.hyg.lib_common.Base.BaseApplication;
import com.hyg.lib_common.DataModel.Music.FavMusic;
import com.hyg.lib_common.DataModel.Music.Music;
import com.hyg.lib_common.DataModel.Music.MusicCategoryData;
import com.hyg.lib_common.sweetalertdialog.SweetAlertDialog;
import com.hyg.lib_music.R;
import com.hyg.lib_music.adapter.MusicCategoryViewBinder;
import com.hyg.lib_music.adapter.MusicCountViewBinder;
import com.hyg.lib_music.adapter.MusicViewBinder;
import com.hyg.lib_music.presenter.MusicListContract;
import com.hyg.lib_music.presenter.di.components.DaggerActivityComponent;
import com.hyg.lib_music.service.MusicService;
import com.hyg.lib_music.util.ApplicationComponentUtil;
import com.hyg.lib_music.util.MusicChangeEvent;
import com.hyg.lib_music.util.MusicFavManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import javax.inject.Inject;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

import static me.drakeet.multitype.MultiTypeAsserts.assertAllRegistered;
import static me.drakeet.multitype.MultiTypeAsserts.assertHasTheSameAdapter;

public class MusicListFragment extends BaseFragment  implements MusicListContract.View{

    private MusicCategoryData mCategory;

    private List<Music> musicList;

    @Inject
    MusicListContract.Presenter presenter;

    private MultiTypeAdapter mAdapter;

    private Items items;

    private MusicService.MusicServiceBinder serviceBinder;

    public SweetAlertDialog pDialog = null;

    public static MusicListFragment newInstance(MusicCategoryData data) {
        MusicListFragment fragment = new MusicListFragment();
        Bundle args = new Bundle();
        args.putSerializable("category" , data);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_music_system, container, false);

        RecyclerView mRecyclerView = view.findViewById(R.id.recycler_view);

        //Dagger注入
        DaggerActivityComponent.builder()
                .applicationComponent(new ApplicationComponentUtil(BaseApplication.getInstance()).getComponent())
                .build()
                .inject(this);

        if (getArguments() != null) {
            mCategory = (MusicCategoryData)getArguments().getSerializable("category");
        }

        //TODO 测试
//        mCategory.id = 39;
//        mCategory.logoUrl = "https://hyg-head-icon.oss-cn-beijing.aliyuncs.com/13821330299-head-1561085730944.jpg";

        presenter.setContractView(this);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        MusicViewBinder musicViewBinder = new MusicViewBinder();
        musicViewBinder.setOnMusicClickListener(new MusicViewBinder.OnMusicClickListener() {
            @Override
            public void onItemClick(View view, Music music) {
                int id = view.getId();
                if (id == R.id.music_child) {
                    if (MusicFavManager.sharedManager(getActivity()).getAllowMobile() == false && NetworkUtils.isMobileType(getContext())) {
                        if (pDialog != null && pDialog.isShowing()) {
                            pDialog.dismiss();
                        }
                        pDialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.NORMAL_TYPE);
//                            pDialog.setTitleText("格式错误");
                        pDialog.setContentText("您当前正在使用移动流量进行缓存播放音乐，是否继续播放音乐");
                        Music finalMusic = music;
                        pDialog.setConfirmButton("继续", new SweetAlertDialog.OnSweetClickListener() {
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismiss();
                                MusicFavManager.sharedManager(getActivity()).setAllowMobile(true);
                                serviceBinder.addPlayList(musicList, finalMusic);
                            }
                        });
                        pDialog.setCancelButton("停止", new SweetAlertDialog.OnSweetClickListener() {
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismiss();
                            }
                        });
                        pDialog.show();
                    } else {
                        serviceBinder.addPlayList(musicList, music);
                    }
//                        serviceBinder.addPlayList(musicList,music);
                } else if (id == R.id.fav) {
                    if (music.isFav) {
                        presenter.removeFavorite(music.id);
                    } else {
                        presenter.addFavorite(music.id);
                    }
                }
            }

        });
        MusicCategoryViewBinder musicCategoryViewBinder = new MusicCategoryViewBinder();
        musicCategoryViewBinder.setOnMusicCategoryClickListener(new MusicCategoryViewBinder.OnMusicCategoryClickListener() {
            @Override
            public void onItemClick(View view, MusicCategoryData musicCategoryData) {
                musicCategoryData.isExpand = !musicCategoryData.isExpand;
            }

        });
        mAdapter = new MultiTypeAdapter();
        mAdapter.register(Music.class, musicViewBinder);
        mAdapter.register(String.class, new MusicCountViewBinder());
        mAdapter.register(MusicCategoryData.class, musicCategoryViewBinder);

        mRecyclerView.setAdapter(mAdapter);
        assertHasTheSameAdapter(mRecyclerView, mAdapter);

        //绑定播放服务
        Intent i = new Intent(getActivity(), MusicService.class);
        getActivity().bindService(i, mServiceConnection, getActivity().BIND_AUTO_CREATE);

        presenter.getMusicList(mCategory.id);

        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            this.refresh();
        } else {
            // 隐藏当前的fragment
        }
    }

    @Override
    public void setMusicListData(List<Music> musicList) {
        this.musicList = musicList;
        refresh();
    }

    @Override
    public void addFavorite(int musicId) {
        //添加本地收藏
        for(Music music:this.musicList) {
            if (music.id == musicId) {
                Toast.makeText(this.getActivity(), "已将“"+music.musicName+"”添加到【我的收藏】", Toast.LENGTH_SHORT).show();
                MusicFavManager.sharedManager().addFavorite(music);
                break;
            }
        }
        //更新列表
        EventBus.getDefault().post(new MusicChangeEvent(musicId));
    }

    @Override
    public void removeFavorite(int musicId) {
        for(Music music:this.musicList) {
            if (music.id == musicId) {
                Toast.makeText(this.getActivity(), "已将“"+music.musicName+"”从【我的收藏】中删除", Toast.LENGTH_SHORT).show();
                break;
            }
        }
        //删除本地收藏
        MusicFavManager.sharedManager().removeFavorite(musicId);
        //更新列表
        EventBus.getDefault().post(new MusicChangeEvent(musicId));

//        //正在播放的
//        Music currentMusic = serviceBinder.getCurrentMusic();
//        //是否正在播放
//        if (currentMusic != null && musicId == currentMusic.id){
//            serviceBinder.playNext();
//        }
//        serviceBinder.removeMusicById(musicId);
    }

    private void refresh(){
        if (this.musicList == null) {
            return;
        }
        items = new Items();

        items.add(mCategory);
        items.add(this.musicList.size()+"");

        //正在播放的
        Music currentMusic = serviceBinder.getCurrentMusic();

        List<FavMusic> favList = MusicFavManager.sharedManager().getAll();
        for (int i = 0; i < this.musicList.size(); i++) {

            Music music = this.musicList.get(i);
            //设置背景色
            if(i %2 ==1){
                music.isWhite = true;
            }else{
                music.isWhite = false;
            }
            //确定是否在本地收藏列表
            music.isFav = false;
            for (FavMusic fav : favList){
                if (fav.musicId == music.id){
                    music.isFav = true;
                    break;
                }
            }
            //是否在播放
            if (currentMusic != null && music.id == currentMusic.id){
                music.isPlaying = true;
            } else {
                music.isPlaying = false;
            }

            items.add(music);
        }
        mAdapter.setItems(items);
        mAdapter.notifyDataSetChanged();
        assertAllRegistered(mAdapter, items);
    }

    //定义与服务的连接的匿名类
    private ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //绑定成功后，取得MusicSercice提供的接口
            serviceBinder = (MusicService.MusicServiceBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };


    // 切换音乐消息
    @Subscribe
    public void onMessageEvent(MusicChangeEvent event){
        refresh();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().unbindService(mServiceConnection);
        EventBus.getDefault().unregister(this);
    }
}